package com.bluetrum.devicemanager.cmd.payloadhandler;

import androidx.annotation.NonNull;

import com.bluetrum.devicemanager.models.Multipoint;
import com.bluetrum.devicemanager.models.SinglePoint;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;

public class MultipointPayloadHandler extends PayloadHandler<Multipoint> {

    public MultipointPayloadHandler(@NonNull byte[] payload) {
        super(payload);
    }

    private byte[] deobfuscateAddress(byte[] address) {
        byte[] result = new byte[6];
        for (int i = 0; i < address.length; i++) {
            result[i] = (byte) ((address[i] & 0xFF) ^ 0xAD);
        }
        return result;
    }

    @Override
    public Multipoint call() throws Exception {
        final List<SinglePoint> endpoints = new ArrayList<>();
        final byte[] payload = getPayload();

        if (payload.length > 0) {
            ByteBuffer bb = ByteBuffer.wrap(payload);

            int count = bb.get();

            // 这里考虑了蓝牙名称为空的情况
            while (bb.remaining() >= 8) {
                int length = bb.get();

                byte[] addressBytes = new byte[6];
                bb.get(addressBytes);
                byte[] address = deobfuscateAddress(addressBytes);

                int state = bb.get();

                byte[] nameBytes = new byte[length - 7]; // -address, -state
                bb.get(nameBytes);
                String name = new String(nameBytes);

                endpoints.add(new SinglePoint(address, name, state));
            }
        }

        return new Multipoint(endpoints);
    }
}
